<?php

require_once WACT_ROOT . '/db/db.inc.php';
require_once WACT_ROOT . '/util/dataspace.inc.php';
require_once $_SERVER["DOCUMENT_ROOT"].'/./model/common/site.php';


class User {

    function &getAdminsList(&$Pager) {
        return DBC::NewPagedRecordSet('SELECT U.*, S.title as siteName
        FROM sport_users U
        left outer join sport_sites S
        on U.signupSiteID = S.siteID
        where U.level=2 ORDER BY U.login', $Pager);
    }

    function &getRegisteredUsersList(&$Pager) {
        return DBC::NewPagedRecordSet('SELECT U.*, S.title as siteName
        FROM sport_users U
        left outer join sport_sites S
        on U.signupSiteID = S.siteID
        where U.level=0 ORDER BY U.login', $Pager);
    }

    // for list
    function &getAuthorsUsersList(&$Pager) {
    	$site_id = Site::getSiteID();
        return DBC::NewPagedRecordSet(
        'SELECT U.*, S.title as siteName,
        F.file_id, F.filename_local, F.path, F.filename_thumb, F.width, F.height
        FROM sport_users U
        left outer join sport_files F
        on U.photo_id=F.file_id
        left outer join sport_sites S
        on U.signupSiteID = S.siteID
        where U.level=1
        and U.signupSiteID = '.DBC::makeLiteral($site_id).'
        ORDER BY U.login', $Pager);
    }

    // for combo box
    function &getAuthorsList() {    	$site_id = Site::getSiteID();
        $rs =& DBC::NewRecordSet('SELECT U.*, S.title as siteName
        FROM sport_users U
        left outer join sport_sites S
        on U.signupSiteID = S.siteID
        where U.level=1 and U.active=1
        and U.signupSiteID = '.DBC::makeLiteral($site_id).'
        ORDER BY U.login');
        $rs->reset();
        $list = array();
        $list[0] = '(ALL)';
        while($rs->next()) {
        	$key = $rs->get('user_id');
        	$login = $rs->get('login');
            $firstname = $rs->get('firstname');
            $lastname = $rs->get('lastname');
            $name = $firstname.' '.$lastname.'('.$login.')';
            $list[$key] = $name;
        }
        return $list;
    }

     // for combo box
    function &getStaffUsers() {
    	$site_id = Site::getSiteID();
        $rs =& DBC::NewRecordSet('SELECT U.*, S.title as siteName
        FROM sport_users U
        left outer join sport_sites S
        on U.signupSiteID = S.siteID
        where U.staff=1 and (U.level=1 or U.level=2) and U.active=1
        and (U.signupSiteID = '.DBC::makeLiteral($site_id).' or  U.level=2)
        ORDER BY U.login');
        $rs->reset();
        $list = array();
        $list[0] = '(Me)';
        while($rs->next()) {
        	$key = $rs->get('user_id');
        	$login = $rs->get('login');
            $firstname = $rs->get('firstname');
            $lastname = $rs->get('lastname');
            $name = $firstname.' '.$lastname.'('.$login.')';
            $list[$key] = $name;
        }
        return $list;
    }

    //get frontpage authors
    function &getFrontpageAuthors() {
    	$site_id = Site::getSiteID();
    	$query="select U.*, S.title as siteName
    	FROM sport_users U
    	left outer join sport_sites S
        on U.signupSiteID = S.siteID
    	where
    	U.level=1 and U.front_page=1 and U.active=1
        and U.signupSiteID = ".DBC::makeLiteral($site_id)."
    	ORDER BY U.lastname, U.firstname";
    	return DBC::NewRecordSet($query);
    }

    function &getNotFrontpageAuthors() {
        $site_id = Site::getSiteID();
    	$rs =& DBC::NewRecordSet('SELECT U.*, S.title as siteName
    	FROM sport_users U
    	left outer join sport_sites S
        on U.signupSiteID = S.siteID
    	where U.level=1 and (U.front_page<>1 or U.front_page is null)
    	and U.signupSiteID = '.DBC::makeLiteral($site_id).'
    	ORDER BY U.lastname,U.firstname');
        //$rs->reset();
        //$mylist = array();
        //$mylist[0] = 'More article writers...';
        //while($rs->next()) {
        	//$mykey = $rs->get('user_id');
            //$firstname = $rs->get('firstname');
            //$lastname = $rs->get('lastname');
            //$name = $firstname.' '.$lastname;
            //$mylist[$mykey] = $name;
        // }
        //return $mylist;
        return $rs;
    }

    // for combo box
    function &getUsersList() {
        $rs =& DBC::NewRecordSet('SELECT U.*
        FROM sport_users U ORDER BY U.login');
        $rs->reset();
        $list = array();
        $list[0] = '(ALL)';
        while($rs->next()) {
        	$key = $rs->get('user_id');
        	$login = $rs->get('login');
            $firstname = $rs->get('firstname');
            $lastname = $rs->get('lastname');
            $name = $firstname.' '.$lastname.'('.$login.')';
            $list[$key] = $name;
        }
        return $list;
    }

    function &getSubscriberUsersList(&$Pager) {
        return DBC::NewPagedRecordSet('SELECT U.*, S.title as siteName, count(SS.id) as number_subscriptions, count(P.payment_id) as number_payments
        		FROM sport_users U
        		inner join sport_subscriptions SS on U.user_id = SS.user_id
        		left outer join sport_payments P on SS.id = P.subscription_id
                left outer join sport_sites S
        		on U.signupSiteID = S.siteID
        		where U.level=0 group by U.user_id ORDER BY U.login', $Pager);
    }

    function &getSubscriberRecord($id) {
        return DBC::FindRecord("SELECT U.*, count(S.id) as number_subscriptions, count(P.payment_id) as number_payments
        FROM sport_users U
        inner join sport_subscriptions S on U.user_id = S.user_id
        left outer join sport_payments P on S.id = P.subscription_id
        where U.user_id=". DBC::makeLiteral($id)." group by U.user_id");
    }


    function &getRecord($id) {
        return DBC::FindRecord("SELECT U.*, F.file_id, F.filename_local, F.path, F.filename_thumb, F.width, F.height FROM sport_users U left outer join sport_files F on U.photo_id=F.file_id WHERE U.user_id=". DBC::makeLiteral($id));
    }

    // this checks whether the user account with the specified login exists
    function &getRecordbyLogin($login){
    	return DBC::FindRecord("SELECT * FROM sport_users WHERE login='$login'");
    }

    // this performs the login and checks the active state and password
    // TO DO: check the active state when logging and encrypt the password
    function &tryLogin($login, $password){
    	return DBC::FindRecord("SELECT * FROM sport_users WHERE login='$login' and password='$password' and `active`>0");
    }

    function delete($id) {
        DBC::execute("DELETE FROM sport_users WHERE user_id=". DBC::makeLiteral($id));
    }

    function deleteSubscriber($id) {
        DBC::execute("DELETE FROM sport_subscriptions WHERE user_id=". DBC::makeLiteral($id));
        DBC::execute("DELETE FROM sport_users WHERE user_id=". DBC::makeLiteral($id));
    }

    function updateAdmin($id, &$data) {
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_users',
            array('login', 'firstname', 'lastname', 'password', 'email'),
            "user_id=". DBC::makeLiteral($id));
    }

     function activate($id,  &$data, $flag) {
     	if ($flag)  $data->set('active',1);
     	else $data->set('active',0);
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_users',
            array('active'),
            "user_id=". DBC::makeLiteral($id));
    }

    function insertAdmin(&$data) {    	$site_id = Site::getSiteID();
    	$data->set('signupSiteID',$site_id);
        $Record =& DBC::NewRecord($data);

        return $Record->insertId('sport_users',
            array('signupSiteID','level','login', 'firstname', 'lastname', 'password', 'email','active','staff','reg_date'),'user_id');
    }

    function insertRegisteredUser(&$data) {
    	$data->set('active',1);
    	$data->set('reg_date', date("Y-m-d") );
    	$site_id = Site::getSiteID();
    	$data->set('signupSiteID',$site_id);
        $Record =& DBC::NewRecord($data);
        return $Record->insertId('sport_users',
            array('signupSiteID','level','login', 'firstname', 'lastname', 'password', 'email','active','staff','reg_date','address1','address2','city','state','zip','home_phone','work_phone','age','country'),'user_id');
    }

     function updateRegisteredUser($id, &$data) {
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_users',
            array('login', 'firstname', 'lastname', 'password', 'email','address1','address2','city','state','zip','home_phone','work_phone','age','country'),
            "user_id=". DBC::makeLiteral($id));
    }

     function insertAuthorUser(&$data) {
     	$site_id = Site::getSiteID();
    	$data->set('signupSiteID',$site_id);
        $Record =& DBC::NewRecord($data);
        return $Record->insertId('sport_users',
            array('signupSiteID','level','login', 'firstname', 'lastname', 'password', 'email','active','staff','reg_date','address1','address2','city','state','zip','home_phone','work_phone','age','country','photo_url','title','front_page'), 'user_id');
    }

    function updateAuthorUser($id, &$data) {
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_users',
            array('login', 'firstname', 'lastname', 'password', 'email','address1','address2','city','state','zip','home_phone','work_phone','age','country','photo_url','title','front_page','staff'),
            "user_id=". DBC::makeLiteral($id));
    }

    function updateSubscriberUser($id, &$data) {
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_users',
            array('login', 'firstname', 'lastname', 'password', 'email','address1','address2','city','state','zip','home_phone','work_phone','age','country','photo_id','title','front_page','staff'),
            "user_id=". DBC::makeLiteral($id));
    }



    function updateUserAccountInfo($id,&$data){
    	$Record =& DBC::NewRecord($data);
        $Record->update('sport_users',
            array('login', 'firstname', 'lastname', 'email','address1','address2','city','state','zip','home_phone','work_phone','age','country'),
            "user_id=". DBC::makeLiteral($id));
    }
    function updateUserPassword($id,&$data){
    	$Record =& DBC::NewRecord($data);
    	$Record->update('sport_users',array('password'),"user_id=". DBC::makeLiteral($id));
    }

    function updateUserPaypalID($user_id, $paypal_email, $paypal_id) {
    	$data =& new DataSpace();
    	$data->set('paypal_id', $paypal_id);
    	$data->set('paypal_email', $paypal_email);
    	$Record =& DBC::NewRecord($data);
    	$Record->update('sport_users',
    	array('paypal_id','paypal_email'),
    	"user_id=". DBC::makeLiteral($user_id));
    }

    // saves user category permissions
    // $data - input array with rows
    function saveAuthorUserPermissions(&$data, $user_id) {
             $ds =& new DataSpace();
             DBC::execute("DELETE FROM sport_category_permissions WHERE user_id=". DBC::makeLiteral($user_id));

    		 foreach($data as $cat_id=>$row) {
    		 	//print_r($row);
                $ds->import($row);
                $Record =& DBC::NewRecord($ds);
       			$Record->insert('sport_category_permissions',
            	array('user_id','category_id', 'normal', 'premium'));
    		 }
    }

    // loads category permissions
    // input: user_id
    // output: array $normal, array $premium
     function loadAuthorUserPermissions($user_id, &$normal, &$premium) {
       	$rs =& DBC::NewRecordSet('SELECT * FROM sport_category_permissions where user_id='. DBC::makeLiteral($user_id));
       	$rs->reset();
       	if (!isset($normal)) $normal = array();
        if (!isset($premium)) $premium = array();
       	while($rs->next()) {
       	    $category_id = $rs->get('category_id');
            $normal_value = $rs->get('normal');
            $premium_value = $rs->get('premium');
            // populate arrays
            if ($normal_value) $normal[] = $category_id;
            if ($premium_value) $premium[] = $category_id;
       	}
     }

     function isUserSubscriptionActive($user_id){
     	$query="select U.user_id from sport_users U, sport_subscriptions S  where ";
     	$query.="U.user_id=S.user_id and level=0 and U.user_id=$user_id and S.status=1";
     	if( DBC::getOneValue($query)!=null) return true;
     	else return false;
     }

     function isUserSubscriber($user_id){
     	$query="select U.user_id from sport_users U, sport_subscriptions S  where ";
     	$query.="U.user_id=S.user_id and level=0 and U.user_id=$user_id ";
     	if( DBC::getOneValue($query)!=null) return true;
     	else return false;
     }

     function isUserArticleWriter($user_id) {
     	$query="select U.user_id from sport_users U  where ";
     	$query.=" level=1 and U.user_id=$user_id ";
     	if( DBC::getOneValue($query)!=null) return true;
     	else return false;
     }

     function isUserStaffArticleWriter($user_id){
     	$query="select U.user_id from sport_users U  where ";
     	$query.=" level=1 and staff=1 and U.user_id=$user_id ";
     	if( DBC::getOneValue($query)!=null) return true;
     	else return false;
     }

     function isExistingUserArticleWriter(&$data) {
     	$level = $data['level'];
     	if ($level==1) return true;
     	else return false;
     }

     function isExistingUserStaffAuthor(&$data) {
     	$level = $data['level'];
     	$staff = $data['staff'];
     	if ($level==1 && $staff) return true;
     	else return false;
     }

     function isExistingUserAdmin(&$data) {
     	$level = $data['level'];
     	$staff = $data['staff'];
     	if ($level==2) return true;
     	else return false;
     }

     function isUserAdmin($user_id){
     	$query="select U.user_id from sport_users U  where ";
     	$query.=" level=2 and U.user_id=$user_id ";
     	if( DBC::getOneValue($query)!=null) return true;
     	else return false;
     }

     function getFullUserName(&$data) {
     	$fname = $data->get('firstname');
     	$lname = $data->get('lastname');
     	$title = $data->get('title');
     	$full  = $fname.' '.$lname;
     	if ( $title ) $full .= ", ".$title;
     	return $full;

     }

}

?>